package top.laoshuzi.common.temp;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;

import com.blankj.utilcode.util.NetworkUtils;

import java.util.ArrayList;
import java.util.List;

public class NetworkStateReceiver extends BroadcastReceiver {

    private static List<NetworkStateListener> networkStateListeners = new ArrayList<>();

    @SuppressLint("MissingPermission")
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
            dispatchNetworkState(NetworkUtils.getNetworkType());
        }
    }

    private void dispatchNetworkState(NetworkUtils.NetworkType networkType) {
        for (NetworkStateListener listener : networkStateListeners) {
            if (null != listener)
                listener.onNetworkChange(networkType);
        }
    }

    public static void addNetworkStateListener(NetworkStateListener listener) {
        networkStateListeners.add(listener);
    }

    public static void removeNetworkStateListener(NetworkStateListener listener) {
        networkStateListeners.remove(listener);
    }

    public interface NetworkStateListener {
        void onNetworkChange(NetworkUtils.NetworkType networkType);
    }


}
